import 'dart:async';

import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/config/configs.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:mi_mang_flutter/utils/utils.dart';
import 'package:mi_mang_flutter/widget/widget_error.dart';
import 'package:mi_mang_flutter/widget/widget_first_refresh.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({
    Key? key,
    required this.url,
    required this.title,
    this.showWebTitle = false,
  }) : super(key: key);

  /// URL
  final String? url;

  /// 默认显示标题
  final String? title;

  /// 是否显示网页标题
  final bool showWebTitle;

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  /// 当前显示层(0:加载层 1:webView层 2:异常层)
  /// 目前没有检测webView异常的回调
  int _index = 0;

  /// 页面title
  String? _title;

  /// 页面title
  String? _errorMsg;

  @override
  void initState() {
    _title = widget.title;
    super.initState();
  }

  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  WebViewController? _webViewController;

  @override
  Widget build(BuildContext context) {
    return PopScope<bool>(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, bool? result) async {
        if (!didPop) {
          if (_webViewController != null) {
            bool canGoBack = await _webViewController!.canGoBack();
            if (canGoBack) {
              // 网页可以返回时，优先返回上一页
              _webViewController!.goBack();
              return Future.value(true);
            }
            return Future.value(false);
          }
        }
        return Future.value(false);
      },
      child: Scaffold(
        appBar: AppBar(
          title: _buildTitle(),
          centerTitle: true,
          elevation: 0.5,
          // 右上角刷新按钮
          // actions: <Widget>[
          //   _buildRefresh(),
          // ],
        ),
        body: Builder(
          builder: (BuildContext context) {
            return IndexedStack(
              index: _index,
              children: <Widget>[
                const WidgetFirstRefresh(),
                _buildWebView(),
                WidgetError(
                  errMsg: _errorMsg ?? "web异常",
                  onPressed: _webReload,
                )
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildWebView() {
    return WebView(
      // 初始load的url
      initialUrl: widget.url,
      // JS执行模式（是否允许JS执行）
      javascriptMode: JavascriptMode.unrestricted,
      // 开启调试识别
      debuggingEnabled: Configs.DEBUG,

      // 在WebView创建完成后调用，只会被调用一次
      onWebViewCreated: (WebViewController webViewController) {
        _webViewController = webViewController;
        _controller.complete(webViewController);
      },
      // JS和Flutter通信的Channel
      javascriptChannels: <JavascriptChannel>[
        _alertJavascriptChannel(context),
      ].toSet(),
      // 路由委托（可以通过在此处拦截url实现JS调用Flutter部分）
      navigationDelegate: (NavigationRequest request) {
        if (request.url.startsWith('tel:')) {
          Utils.launchURL(request.url);
          return NavigationDecision.prevent;
        }
        print('allowing navigation to $request');
        return NavigationDecision.navigate;
      },
      // WebView加载完毕时的回调
      onPageFinished: (String url) {
        setState(() {
          _index = 1;
        });
      },
      onWebResourceError: (error) {
        setState(() {
          _index = 2;
          _errorMsg = error.description.toString();
        });
      },
    );
  }

  /// 右上角添加网页刷新按钮
  // Widget _buildRefresh() {
  //   return FutureBuilder<WebViewController>(
  //     future: _controller.future,
  //     builder:
  //         (BuildContext context, AsyncSnapshot<WebViewController> controller) {
  //       if (controller.hasData &&
  //           controller.connectionState == ConnectionState.done) {
  //         return IconButton(
  //           icon: Icon(Icons.refresh, size: 24),
  //           onPressed: _webReload,
  //         );
  //       }
  //       return Container();
  //     },
  //   );
  // }

  /// 执行网页刷新
  Widget _buildTitle() {
    return FutureBuilder<WebViewController>(
      future: _controller.future,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> controller) {
        if (controller.hasData &&
            controller.connectionState == ConnectionState.done &&
            widget.showWebTitle) {
          controller.data!.getTitle().then((title) {
            if (title!.isNotEmpty) {
              setState(() {
                _title = title;
              });
            }
          });
        }
        return Text(_title!);
      },
    );
  }

  // 刷新操作
  _webReload() {
    _controller.future.then((web) {
      web.reload();
    });
  }

  /// 网页返回
  // _webGoBack() {
  //   _controller.future.then((web) {
  //     web.canGoBack().then((canBack) {
  //       web.goBack();
  //     });
  //   });
  // }

  // JavascriptChannel _alertJavascriptChannel(BuildContext context) {
  //   return JavascriptChannel(
  //     name: 'Toast',
  //     onMessageReceived: (JavascriptMessage message) {
  //       Toast.showInfo(message.message);
  //     },
  //   );
  // }

  /// 执行某一段js代码方法(备用,未测试)
  // _callJS() {
  //   _controller.future.then((webView) {
  //     webView.evaluateJavascript('callJS("visible")').then((result) {
  //       // 执行js返回的结果
  //       print(result.toString());
  //     });
  //   });
  // }

  @override
  void dispose() {
    super.dispose();
  }
}
